package vn.edu.uit.service;

import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;


/**
 * A factory for creating UITSSLSocket objects.
 */
public  class UITSSLSocketFactory extends SSLSocketFactory {

	/** The ssl context. */
	SSLContext sslContext = SSLContext.getInstance("TLS");

	/**
	 * Instantiates a new UIT ssl socket factory.
	 *
	 * @param truststore the truststore
	 * @throws NoSuchAlgorithmException the no such algorithm exception
	 * @throws KeyManagementException the key management exception
	 * @throws KeyStoreException the key store exception
	 * @throws UnrecoverableKeyException the unrecoverable key exception
	 */
	public UITSSLSocketFactory(KeyStore truststore)
			throws NoSuchAlgorithmException, KeyManagementException,
			KeyStoreException, UnrecoverableKeyException {

		super(truststore);
		TrustManager tm = new X509TrustManager() {

			@Override
			public void checkClientTrusted(X509Certificate[] chain,
					String authType) throws CertificateException {
			}

			@Override
			public void checkServerTrusted(X509Certificate[] chain,
					String authType) throws CertificateException {
			}

			@Override
			public X509Certificate[] getAcceptedIssuers() {
				return null;
			}
		};

		sslContext.init(null, new TrustManager[] { tm }, null);
	}
	
	/**
	 * Instantiates a new UIT ssl socket factory.
	 *
	 * @param context the context
	 * @throws KeyManagementException the key management exception
	 * @throws NoSuchAlgorithmException the no such algorithm exception
	 * @throws KeyStoreException the key store exception
	 * @throws UnrecoverableKeyException the unrecoverable key exception
	 */
	public UITSSLSocketFactory(SSLContext context) throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException {
        super(null);
        sslContext = context;
     }
	
	/* (non-Javadoc)
	 * @see org.apache.http.conn.ssl.SSLSocketFactory#createSocket(java.net.Socket, java.lang.String, int, boolean)
	 */
	@Override
	public Socket createSocket(Socket socket, String host, int port,
			boolean autoClose) throws IOException, UnknownHostException {
		return sslContext.getSocketFactory().createSocket(socket, host, port,
				autoClose);
	}

	/* (non-Javadoc)
	 * @see org.apache.http.conn.ssl.SSLSocketFactory#createSocket()
	 */
	@Override
	public Socket createSocket() throws IOException {
		return sslContext.getSocketFactory().createSocket();
	}


	/**
	 * Creates a new UITSSLSocket object.
	 *
	 * @return the http client
	 */
	public static HttpClient createHttpClient() {
		 try {
			 
			 X509TrustManager tm = new X509TrustManager() { 
		            public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
		            }

		            public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
		            }

		            public X509Certificate[] getAcceptedIssuers() {
		                return null;
		            }
		        };
		      X509HostnameVerifier verifier = new X509HostnameVerifier() {
		        	 
	                @Override
	                public void verify(String string, SSLSocket ssls) throws IOException {
	                }
	 
	                @Override
	                public void verify(String string, X509Certificate xc) throws SSLException {
	                }
	 
	                @Override
	                public void verify(String string, String[] strings, String[] strings1) throws SSLException {
	                }
	 
				@Override
				public boolean verify(String string, SSLSession ssls) {
					return true;
				}
	            };
		    HttpParams params = new BasicHttpParams();
		    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
	        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
	        
	        SchemeRegistry registry = new SchemeRegistry();
	        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
	        
	        SSLContext ctx = SSLContext.getInstance("TLS");
	        ctx.init(null, new TrustManager[]{tm}, null);
	        SSLSocketFactory sslSocketFactory = new UITSSLSocketFactory(ctx);//.getSocketFactory();
	        sslSocketFactory.setHostnameVerifier(verifier);
	        sslSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

	        registry.register(new Scheme("https", sslSocketFactory, 443));
	        registry.register(new Scheme("https", sslSocketFactory, 80));

	        ClientConnectionManager cm = new ThreadSafeClientConnManager(params, registry);

	        HttpClient client = new DefaultHttpClient(cm, params);
	        HttpConnectionParams.setConnectionTimeout(client.getParams(), 180000);   

	        return client;
	

		 } catch (Exception ex) {
		        return null;
		}
	}

	
}
